package com.zj;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.zj.bean.User;
import com.zj.constants.Default;

import cn.hn.java.summer.mvc.WebContext;

public class MyActionInterceptor extends HandlerInterceptorAdapter {
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//为上下文准备response
		WebContext.preperedResponse(response);
		//登录检测
		String root=request.getContextPath();
		String url=request.getRequestURI();
		//登录的用户
		User user=WebContext.getSessionCookie(Default.USER_SESSION_KEY,User.class);
		if(
				(user==null) &&
			!url.startsWith(root+"/regeist")&&
			!url.startsWith(root+"/login")&&
			!url.contains("test")
		){
			WebContext.redirectTo("/login.html");
		}else if(user == null && url.endsWith(".json") && !url.startsWith(root+"/login")){
			WebContext.setRequestAttribute(cn.hn.java.summer.constants.Default.ERROR_IN_REQUEST_KEY, "用户未登录或已超时，请重新登录");
		}

		return super.preHandle(request, response, handler);
	}
}
